package com.eagle.view.activity;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import com.eagle.EApplication;
import com.eagle.R;
import com.eagle.support.constants.Constants;
import com.eagle.support.utils.ToastUtils;
import com.eagle.view.activity.base.BaseCallActivity;
import com.eagle.view.fragment.live.FragmentAudienceLiveShow;
import com.eagle.view.fragment.live.FragmentLiveShowOperation;
import com.eagle.view.fragment.live.FragmentMasterLiveShow;
import com.eagle.view.fragment.menu.FragmentMenu;
import com.eagle.view.widget.base.ETextView;
import com.github.javiersantos.materialstyleddialogs.MaterialStyledDialog;
import com.kinstalk.voip.sdk.EngineSdkCallMode;
import com.kinstalk.voip.sdk.EngineSdkCallState;
import com.kinstalk.voip.sdk.EngineSdkUserRole;
import com.kinstalk.voip.sdk.EngineSdkVideoPixelFormat;
import com.kinstalk.voip.sdk.logic.sip.aidl.model.CallInfo;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.FragmentById;
import org.androidannotations.annotations.ViewById;

/**
 * Created by gc on 2017/1/14.
 */
@EActivity(R.layout.activity_live_show)
public class LiveShowActivity extends BaseCallActivity {

    @FragmentById(R.id.fragment_live_master)
    protected FragmentMasterLiveShow mMasterLiveShow;

    @FragmentById(R.id.fragment_live_audience)
    protected FragmentAudienceLiveShow mAudienceLiveShow;

    @FragmentById(R.id.fragment_live_operation)
    protected FragmentLiveShowOperation mOperationLiveShow;

    @FragmentById(R.id.fragment_live_menu)
    protected FragmentMenu mMenuLiveShow;

    @ViewById(R.id.layout_parent)
    protected RelativeLayout mLayoutParent;

    @ViewById(R.id.layout_live_menu)
    protected RelativeLayout mLayoutMenu;

    @ViewById(R.id.layout_live_info)
    protected RelativeLayout mLayoutLiveInfo;

    @ViewById(R.id.tv_name)
    protected ETextView mTvName;

    @ViewById(R.id.tv_room_online)
    protected ETextView mTvRoomInfo;

    private String mRoomId;

    private int mPersonCount = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setDarkStatusIcon(true);
        initExplodeTransition();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        mCallHelper.callMode(EngineSdkCallMode.ES_CM_TYPE_LIVE.swigValue());
    }

    @AfterViews
    void initView() {
        mTvName.setText(EApplication.getSharedPreferences().getString(Constants.LOGIN_UID, ""));
        getSupportFragmentManager().beginTransaction().hide(mMenuLiveShow).hide(mMasterLiveShow).hide(mAudienceLiveShow).show(mOperationLiveShow).commitAllowingStateLoss();
    }

    @Override
    public void onCallStateHandler(CallInfo call, int state) {
        super.onCallStateHandler(call, state);
        switch (EngineSdkCallState.swigToEnum(state)) {
            case ES_STATE_ON_CALL_IN_ACTIVE_SESSION:
                mOperationLiveShow.dismissLoading();
                if (!TextUtils.isEmpty(mCallHelper.getChannelId())) {
                    handlerFullscreen(true);
                    new Handler().postDelayed(() -> {
                        if (mOperationLiveShow.isMaster()) {
                            mCallHelper.userRole(EngineSdkUserRole.ES_UR_TYPE_MASTER.swigValue());
                            getSupportFragmentManager().beginTransaction().show(mMasterLiveShow).hide(mOperationLiveShow).commitAllowingStateLoss();
                        } else {
                            mCallHelper.userRole(EngineSdkUserRole.ES_UR_TYPE_AUDIENCE.swigValue());
                            getSupportFragmentManager().beginTransaction().show(mAudienceLiveShow).hide(mOperationLiveShow).commitAllowingStateLoss();
                        }

                        mLayoutMenu.setVisibility(View.VISIBLE);
                        mLayoutLiveInfo.setVisibility(View.VISIBLE);
                    }, 500);
                } else {
                    mCallHelper.handlerServerError();
                    ToastUtils.showToast(this, "服务器开小差了, 请稍后重试", R.id.layout_parent);
                }
                break;
            case ES_STATE_ON_CALL_INCOMMING_CALL:
                mOperationLiveShow.dismissLoading();
                break;
            case ES_STATE_ON_CALL_CALL_ENDED:
                handlerEnded();
                break;
        }
    }

    private void handlerEnded() {
        dismissLoading();

        mLayoutMenu.setVisibility(View.GONE);
        mLayoutLiveInfo.setVisibility(View.GONE);

        if (mMenuLiveShow.isShowing()) {
            mMenuLiveShow.hideDialog();
        }

        if (!mMasterLiveShow.isHidden()) {
            mMasterLiveShow.onHandlerCamera(false);
        }
        if (!mAudienceLiveShow.isHidden()) {
            mAudienceLiveShow.onHandlerCamera(false);
        }

        new Handler().postDelayed(() -> finishPage(), 300);
    }

    private void handlerFullscreen(boolean fullscreen) {
        if (fullscreen) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            mLayoutParent.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
            WindowManager.LayoutParams params = getWindow().getAttributes();
            params.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(params);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            setDarkStatusIcon(true);
            WindowManager.LayoutParams params = getWindow().getAttributes();
            params.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(params);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
        }
    }

    @Override
    public void onMessageSendResult(String roomId) {
        super.onMessageSendResult(roomId);
        setRoomId(roomId);
    }

    @Override
    public void onMainVideoDataInCall(long callToken, long pointer, int width, int height, char rotation, EngineSdkVideoPixelFormat format, long channelId) {
        super.onMainVideoDataInCall(callToken, pointer, width, height, rotation, format, channelId);
        if (!mMasterLiveShow.isHidden()) {
            mMasterLiveShow.onMainVideoDataInCall(pointer, width, height, rotation);
        }

        if (!mAudienceLiveShow.isHidden()) {
            mAudienceLiveShow.onMainVideoDataInCall(pointer, width, height, rotation);
        }
    }

    @Override
    protected void receiverSpeed(String rx, String tx) {
        if (!mMasterLiveShow.isHidden()) {
            mMasterLiveShow.receiverSpeed(rx, tx);
        }

        if (!mAudienceLiveShow.isHidden()) {
            mAudienceLiveShow.receiverSpeed(rx, tx);
        }
    }

    @Click(R.id.layout_live_menu)
    protected void onMenu() {
        if (mOperationLiveShow.isHidden()) {
            getSupportFragmentManager().beginTransaction().show(mMenuLiveShow).commitAllowingStateLoss();
            mMenuLiveShow.showDialog(mOperationLiveShow.isMaster() ? FragmentMenu.FROM_LIVE_SHOW_MASTER : FragmentMenu.FROM_LIVE_SHOW_AUDIENCE);
        }
    }


    /**
     * 弹出退出直播
     */
    public void popQuitLiveDialog() {
        new MaterialStyledDialog.Builder(this)
                .setHeaderColorInt(R.color.gray_transparent)
                .setDescription("Whether to quit live?")
                .setPositiveText("OK")
                .setNegativeText("CANCEL")
                .setCancelable(true)
                .onPositive((dialog, which) -> {
                    showLoading();
                    //如果连麦， 先退出连麦
                    if (mConnected) {
                        mCallHelper.leaveConnectBySlaver();
                    }
                    mCallHelper.quitLive();
                    handlerEnded();
                })
                .show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isLoading()) {
                dismissLoading();
                return true;
            }

            if (mMenuLiveShow.isShowing()) {
                mMenuLiveShow.hideDialog();
                return true;
            }

            if (!mMasterLiveShow.isHidden() || !mAudienceLiveShow.isHidden()) {
                popQuitLiveDialog();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 设置房间号
     */
    public void setRoomId(String roomId) {
        this.mRoomId = roomId;
        mTvRoomInfo.setText(getString(R.string.room_info, mRoomId, mPersonCount));
        mCallHelper.roomId(mRoomId);
    }

    /**
     * 连麦状态
     */
    @Override
    public void refreshConnectState(boolean connected) {
        mConnected = connected;
        if (!mAudienceLiveShow.isHidden()) {
            mAudienceLiveShow.setConnected(connected);
        }
    }

    /**
     * 是否连麦
     */
    private boolean mConnected;

    /**
     * 切换镜头
     */
    @Override
    public void switchCamera() {
        if (!mMasterLiveShow.isHidden()) mMasterLiveShow.switchCamera();
        if (!mAudienceLiveShow.isHidden()) mAudienceLiveShow.switchCamera();
    }

    /**
     * 禁用预览
     */
    @Override
    public void hideCamera(boolean hide) {
        if (!mMasterLiveShow.isHidden()) mMasterLiveShow.hideCamera(hide);
        if (!mAudienceLiveShow.isHidden()) mAudienceLiveShow.hideCamera(hide);
    }
}
